package me.caofeng.service;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.response.AlipayTradePrecreateResponse;
import com.alipay.demo.trade.config.Configs;
import com.alipay.demo.trade.model.builder.AlipayTradePrecreateRequestBuilder;
import com.alipay.demo.trade.model.builder.AlipayTradeQueryRequestBuilder;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.alipay.demo.trade.model.result.AlipayF2FQueryResult;
import com.alipay.demo.trade.service.AlipayTradeService;
import com.alipay.demo.trade.service.impl.AlipayTradeServiceImpl;
import me.caofeng.dao.OrderMapper;
import me.caofeng.enums.ResponseCode;
import me.caofeng.pojo.AlipayInfo;
import me.caofeng.pojo.Order;
import me.caofeng.pojo.Response;
import me.caofeng.service.api.IAlipayService;
import me.caofeng.util.CheckUtil;
import me.caofeng.util.JsonUtil;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Map;


/**
 * Copyright © 2017曹峰. All rights reserved.
 *
 * @Prject: mall
 * @Package: me.caofeng.service
 * @Description:
 * @Author: 曹峰 blog.caofeng.me
 * @Date: 2017-06-28 19:03
 * @Version: V1.0
 */
@Service
@Transactional
public class AlipayService implements IAlipayService {
    private static Logger LOGGER = LogManager.getLogger(AlipayService.class);
    private static AlipayTradeService tradeService;

    @Autowired
    private OrderMapper orderMapper;
    //加载支付宝支付配置

    static {
        Configs.init("alipay.properties");
        tradeService = new AlipayTradeServiceImpl.ClientBuilder().build();
    }

    @Override
    public Response<String> pay(AlipayTradePrecreateRequestBuilder builder) {
        AlipayF2FPrecreateResult result = tradeService.tradePrecreate(builder);
        String error = null;
        switch (result.getTradeStatus()) {
            case SUCCESS:
                AlipayTradePrecreateResponse response = result.getResponse();
                return Response.response(ResponseCode.SUCCESS, "统一下单成功", response.getQrCode());
            case FAILED:
                error = "支付宝预下单失败";
                break;
            case UNKNOWN:
                error = "系统异常";
                break;
            default:
                error = "不支持的交易状态,交易返回异常";
                break;
        }
        LOGGER.error(error);
        return Response.response(ResponseCode.ERROR, "统一下单失败 ", error);
    }

    @Override
    public Response getPayStatus(String orderId) {
        // 创建查询请求builder，设置请求参数
        AlipayTradeQueryRequestBuilder builder = new AlipayTradeQueryRequestBuilder()
                .setOutTradeNo(orderId);

        AlipayF2FQueryResult result = tradeService.queryTradeResult(builder);

        switch (result.getTradeStatus()) {
            case SUCCESS:
                LOGGER.info("查询返回该订单支付成功: )");
                return Response.response(ResponseCode.SUCCESS, "订单已支付", null);
            case FAILED:
                LOGGER.info("查询返回该订单支付失败或被关闭!!!");
                return Response.response(ResponseCode.ERROR, "订单支付失败或被关闭", null);

            case UNKNOWN:
                LOGGER.info("系统异常，订单支付状态未知!!!");
                return Response.response(ResponseCode.ERROR, "系统异常,订单状态未知", null);
            default:
                LOGGER.info("不支持的交易状态，交易返回异常!!!");
                return Response.response(ResponseCode.ILLEGAL_ARGUMENT, "不支持的交易", null);
        }

    }

    @Override
    public Object verifyCallback(Map<String, String> map) {
        //验证签名
        if (!verifySign(map)) {
            return "failure";
        }

        //将map参数转化为实体对象
        AlipayInfo alipayInfo = new AlipayInfo(map);

        LOGGER.info(JsonUtil.toJSon(alipayInfo));

        // 验证订单是否为本系统订单,验证订单编号，订单金额
        String userId = orderMapper.verifyAlipayCallback(alipayInfo.getOrderId(), alipayInfo.getTotalAmount());
        LOGGER.info("用户编号 "+userId);
        if (CheckUtil.isEmpty(userId)) {
            return "failure";
        }

        LOGGER.info("更新支付信息");
        // 更新支付信息
        alipayInfo.setUserId(userId);

        int payInfoRow = orderMapper.updateAlipayInfo(alipayInfo);

        LOGGER.info("更新订单信息");
        // 更新订单信息
        int orderRow = orderMapper.updateOrder(new Order(alipayInfo));

        if (payInfoRow != 1 || orderRow != 1) {
            LOGGER.error("更新订单状态失败");
            return "failure";
        }
        LOGGER.info("修改订单状态成功");
        return "success";
    }

    //验证签名
    private boolean verifySign(Map<String, String> map) {
        try {
            boolean signVerified = AlipaySignature.rsaCheckV1(map,
                    Configs.getAlipayPublicKey(), "utf-8", Configs.getSignType());
            return signVerified;
        } catch (AlipayApiException e) {
            LOGGER.error(e);
            return false;
        }
    }

}
